#include "Utils.h"
#include <windows.h>

typedef BOOL (WINAPI *P_GDFSE)(LPCTSTR, PULARGE_INTEGER,PULARGE_INTEGER, PULARGE_INTEGER);

UInt64  Utils::GetFreeDiskSpaceX(string dir)
{
	BOOL  fResult;
	unsigned __int64 i64FreeBytesToCaller,
						   i64TotalBytes,
						   i64FreeBytes;
	DWORD dwSectPerClust,
            dwBytesPerSect,
            dwFreeClusters,
            dwTotalClusters;

	P_GDFSE pGetDiskFreeSpaceEx = NULL;
/*
         Use GetDiskFreeSpaceEx if available; otherwise, use
         GetDiskFreeSpace.

         Note: Since GetDiskFreeSpaceEx is not in Windows 95 Retail, we
         dynamically link to it and only call it if it is present.  We 
         don't need to call LoadLibrary on KERNEL32.DLL because it is 
         already loaded into every Win32 process's address space.
      */ 
      pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress (GetModuleHandle ("kernel32.dll"),"GetDiskFreeSpaceExA");
      if (pGetDiskFreeSpaceEx)
      {
		  fResult = pGetDiskFreeSpaceEx (dir.c_str(),
                                 (PULARGE_INTEGER)&i64FreeBytesToCaller,
                                 (PULARGE_INTEGER)&i64TotalBytes,
                                 (PULARGE_INTEGER)&i64FreeBytes);
         if (fResult)
         {
            //printf ("\n\nGetDiskFreeSpaceEx reports\n\n");
            //printf ("Available space to caller = %I64u MB\n",
            //        i64FreeBytesToCaller / (1024*1024));
            //printf ("Total space               = %I64u MB\n",
            //        i64TotalBytes / (1024*1024));
            //printf ("Free space on drive       = %I64u MB\n",
            //        i64FreeBytes / (1024*1024));

			return i64FreeBytesToCaller / (1024*1024);
         }
      }
      else
      {
         fResult = GetDiskFreeSpace (dir.c_str(), 
                                     &dwSectPerClust,
                                     &dwBytesPerSect, 
                                     &dwFreeClusters,
                                     &dwTotalClusters);
         if (fResult)
         {
            /* force 64-bit math */ 
            i64TotalBytes = (__int64)dwTotalClusters * dwSectPerClust *
                              dwBytesPerSect;
            i64FreeBytes = (__int64)dwFreeClusters * dwSectPerClust *
                              dwBytesPerSect;

            //printf ("GetDiskFreeSpace reports\n\n");
            //printf ("Free space  = %I64u MB\n", 
            //        i64FreeBytes / (1024*1024));
            //printf ("Total space = %I64u MB\n", 
            //        i64TotalBytes / (1024*1024));
         
			return i64FreeBytes / (1024*1024);
		 }
      }

	  return 0;
}

